var express = require('express');
var router = express.Router();
var comData = require('../models/comData');
var v_user = require('../models/validate/user');
/* GET home page. */
router.get('/index',v_user.checkLogin, function (req, res, next) {
    //文章列表
    //获取用户列表
    Model('user').find({},{_id:1,username:1,is_online:1},function(err,data){
        res.render('chat/index', {title: '聊天室',userList:data});
    });
});
//聊天室
var server = require('http').createServer(function(req,res){});
var io = require('socket.io')(server);
var online_count = 0;
var online_user={};
//获取在聊天室的用户
io.on('connection', function (socket) {
    online_count += 1;
    socket.send({user:'系统',content:'欢迎加入群聊！'});
    socket.on('message', function (msg) {
        //把接受的消息发送给除发送者以外的所有聊天室的人
        if(msg.id){
            var user_id=msg.id;
            Model('user').update({_id:user_id},{is_online:1},function(err,data){});
            online_user[user_id]=socket;
        }else if(msg.receive_id){
            for(var s in online_user){
                var content=msg.content.replace(/^@[a-zA-Z0-9]*\b:/,'私聊:');
                if(String(s)==String(msg.receive_id)){
                    online_user[s].send({user:msg.user_name,content:content});
                }
            }
        }else{
            for(var s in online_user){
                if(String(s)!=String(msg.user_id)){
                    online_user[s].send({user:msg.user_name,content:msg.content});
                }
            }
        }
    });
    socket.on('disconnect',function(evt) {//断开连接
        online_count -=1;
        for(var s in online_user){
            if(online_user[s].id==this.id){
                Model('user').update({_id:s},{is_online:0},function(err,data){});
                delete online_user[s];
            }
        }
        // Model('user').update({_id:user_id},{is_online:0},function(err,data){});
    })
});
server.listen(8080);
module.exports = router;
